#!/usr/bin/env bash

if [ $# -ne 2 ]; then
   cat << EOS
Use: version_cmp x.y.z m.n.o
 or  version_cmp-metadata x.y.z m.n.o+metadata
Exit status:
0: v1 = v2
1: v1 < v2
2: v1 > v2
EOS
   exit 127
fi

# First argument processing
s1=${1#*[-+]}
f=${1%[-+]*}
c=${f//[^.]/}
f=${f//./}
let "v1 = f * 10 ** ( 2 - ${#c} )"

# Second argument processing
s2=${2#*[-+]}
f=${2%[-+]*}
c=${f//[^.]/}
f=${f//./}
let "v2 = f * 10 ** ( 2 - ${#c} )"

if [ "$v1" -lt "$v2" ]; then
   exit 1
elif [ "$v1" -gt "$v2" ]; then
   exit 2
else
   if [ "$s1" \< "$s2" ]; then
      exit 1
   elif [ "$s1" \> "$s2" ]; then
      exit 2
   else
      exit 0
   fi
fi
